﻿#region Namespace
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.Sql;
using System.Data.SqlClient;
using EB.SQL;
using EB.BPARequestManagement;
using Eb.MessageBox;
#endregion

public partial class WebUserControl : System.Web.UI.UserControl
{

    #region Fields
    PaymentRequestHandler _paymentRequestHandler; 
    paymentreqstgenclass _paymentreqstgenclass;
    static int _RequestId=0;
    static int requestListUniqRecordNumber = 0;
    RequestCreate requestCreate = new RequestCreate();
    Purchase.Purchase purchase = new Purchase.Purchase();
    static int linkKey = 0;
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {

        _paymentRequestHandler = new PaymentRequestHandler();
        _paymentreqstgenclass = new paymentreqstgenclass();
       // _paymentRequestHandler.Constring = ((String)Session["ConnectionString"]).ToString();
        _paymentRequestHandler.Constring =  ConfigurationManager.ConnectionStrings["connectUserManager"].ToString();


        //_paymentreqstgenclass.Constring = ((String)Session["ConnectionString"]).ToString();
        //_paymentreqstgenclass.RequesterID = ((String)Session["UserId"]).ToString();

        string pathurl = ((System.Web.HttpRequest)((HttpContext.Current.Request))).Url.AbsoluteUri;
        if (pathurl.ToLower().EndsWith("aspx"))
        {
            if (Session["controlPath"] != null)
            {
                DisplayPaymentRequest();
            }
            else
            {
                Session["hasrequestLinkId"] = null;
                Session["requestTypeId"] = null;
                Session["controlPath"] = null;
            }
        }
        else if (Request.QueryString["Sel"] != null)
        {
            string URL = Request.QueryString["Sel"].ToString();
            string FileName = URL.Substring(URL.LastIndexOf("/") + 1, (URL.Length - URL.LastIndexOf("/") - 1));
            if (FileName == "paymentreqUserControl.ascx")
            {
                Session["hasrequestLinkId"] = null;
                Session["requestTypeId"] = null;
                Session["controlPath"] = null;

            }
            else if (FileName == "TaskList.ascx")
            {
                if (Session["controlPath"] != null)
                {
                    DisplayPaymentRequest();
                    //btnViewPurchaseReq.Visible = false;
                   // Button6.Visible = false;
                }
            }
        }
        else if (Request.QueryString["linkKey"].ToString() != null && Request.QueryString["RequestType"].ToString() !=null)
        {       
            DisplayPaymentRequest();
        }
    }
    protected void DisplayPaymentRequest()
    {
        if (Session["hasrequestLinkId"] != null && Session["requestTypeId"] != null)
        {
            int typeId = _paymentRequestHandler.GetPaymentMode(Convert.ToInt16(Session["hasrequestLinkId"]));
            int uniqId = Convert.ToInt16(Session["hasrequestLinkId"]);
            DataSet paymentRequestDS = _paymentRequestHandler.GetPaymentRequestByPaymentId(uniqId);
            if (paymentRequestDS.Tables[0].Rows.Count > 0)
            {

                Save.Visible = false;
                Paymenttype.SelectedValue = paymentRequestDS.Tables[0].Rows[0]["PaymentType"].ToString();
                Paymenttype.Enabled = false;
                Purpose.Text = paymentRequestDS.Tables[0].Rows[0]["Purpose"].ToString();
                paidto.Text =  paymentRequestDS.Tables[0].Rows[0]["PaidTo"].ToString(); 
                amount.Text =  paymentRequestDS.Tables[0].Rows[0]["Amount"].ToString();
                requestdate.Text = paymentRequestDS.Tables[0].Rows[0]["paymentdate"].ToString();
                Paymentmode.SelectedValue = paymentRequestDS.Tables[0].Rows[0]["PaymentType"].ToString();
                Purpose.Enabled = false;
                paidto.Enabled = false;
                amount.Enabled = false;
                requestdate.Enabled = false;
                Paymentmode.Enabled = false;
            }
        }
    }
    protected void Save_Click(object sender, EventArgs e)
    {
        try
        {
            int reqId = 0;
            if (Session["UserId"] != null)
                reqId = Convert.ToInt16(Session["UserId"].ToString());

            if (Save.Text == "Next")
            {

                MultiView1.ActiveViewIndex++;
            }
            else if (Save.Text == "Update")
            {
                Forward.Visible = true;
           
            //SqlConnection sqlCon = new SqlConnection();
            //SqlCommand sqlCommand = new SqlCommand();

            //sqlCon.ConnectionString = ((String)Session["ConnectionString"]).ToString();
            //sqlCommand.Connection = sqlCon;
           
            //sqlCon.Open();
            //string sqlCmd = "update  PaymentRequestList set ";
                //RequestID,PaymentType,PaidTo, Purpose,Amount,BillNo,BillDate,BillAmount,Balance,PaymentMode,OrderNo,Status,paymentdate where PaymentID=" + _idkey + "";
                _paymentRequestHandler.PaymentType = int.Parse(Paymenttype.SelectedItem.Value.ToString());
                _paymentRequestHandler.Purpose = Purpose.Text;
                _paymentRequestHandler.PaidTo = paidto.Text;
                _paymentRequestHandler.Amount = amount.Text;
                _paymentRequestHandler.PaymentDate = requestdate.Text;
                _paymentRequestHandler.PaymentMode = int.Parse(Paymentmode.SelectedItem.Value.ToString());
                _paymentRequestHandler.Balance = "0";
                _paymentRequestHandler.BillAmount = "0";
                _paymentRequestHandler.BillNo = string.Empty;
                _paymentRequestHandler.BillDate = string.Empty;
                _paymentRequestHandler.UpdatePaymentRequest();
          

           }
         
            else
            {

                _paymentRequestHandler.PaymentType = int.Parse(Paymenttype.SelectedItem.Value.ToString());
                _paymentRequestHandler.Purpose = Purpose.Text;
                _paymentRequestHandler.PaidTo = paidto.Text;
                _paymentRequestHandler.Amount = amount.Text;
                _paymentRequestHandler.PaymentDate = requestdate.Text;
                _paymentRequestHandler.PaymentMode = int.Parse(Paymentmode.SelectedItem.Value.ToString());
              int Paymentid=  _paymentRequestHandler.AddAPaymentRequest();

              linkKey = Paymentid;
              int requestTypeId = requestCreate.FindRequestTypeId("PaymentRequest");
              int id = requestCreate.CreateRequest("PaymentRequest", 0, linkKey);
              bool status = purchase.UpdateReQuestStatus(linkKey, requestTypeId, reqId);
              _RequestId = id;


            //  int id = requestlist(Paymentid);
              UpdatePaymentList(id);
                Save.Text = "Update";
                Forward.Visible = true;
                MessageBox.Show("Successfully Inserted");
            }

        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "PaymentRequest Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }
   

    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        MultiView1.ActiveViewIndex--;

    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (Paymenttype.SelectedItem.Text.ToString().Trim() == "MaterialPurchase")
        {
            Save.Text = "Next";
        }
        else if (Paymenttype.SelectedItem.Text.ToString().Trim() == "Purchase")
        {
            Save.Text = "Submit";
        }
        else if (Paymenttype.SelectedItem.Text.ToString().Trim() == "ServiceFee")
        {
            Save.Text = "Next";
        }
        else if (Paymenttype.SelectedItem.Text.ToString().Trim() == "Salary")
        {
            Save.Text = "Save";
        }
        else if (Paymenttype.SelectedItem.Text.ToString().Trim() == "TA")
        {
            Save.Text = "Submit";
        }
        else if (Paymenttype.SelectedItem.Text.ToString().Trim() == "Incentive")
        {
            Save.Text = "Submit";
        }
        else if (Paymenttype.SelectedItem.Text.ToString().Trim() == "InstallationExpense")
        {
            Save.Text = "Submit";
        }

        else if (Paymenttype.SelectedItem.Text.ToString().Trim() == "SupportExpense")
        {
            Save.Text = "Submit";
        }                     
        else 
        {
            Save.Text = "Submit";
        }
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        try
        {
            int reqId = 0;
            if (Session["UserId"] != null)
                reqId = Convert.ToInt16(Session["UserId"].ToString());

            _paymentRequestHandler.PaymentType = int.Parse(Paymenttype.SelectedItem.Value.ToString());
            _paymentRequestHandler.Purpose = Purpose.Text;
            _paymentRequestHandler.PaidTo = paidto.Text;
            _paymentRequestHandler.Amount = amount.Text;
            _paymentRequestHandler.PaymentDate = requestdate.Text;

            _paymentRequestHandler.OrderNo = orderno.Text;
            _paymentRequestHandler.BillAmount = billamount.Text;
            _paymentRequestHandler.BillDate = billdate.Text;
            _paymentRequestHandler.BillNo = Billno.Text;
            _paymentRequestHandler.Balance = balance.Text;
            _paymentRequestHandler.PaymentMode = int.Parse(Paymentmode.SelectedItem.Value.ToString());
            if (Button3.Text == "Update")
            {
                Forward1.Visible = true;
                
                _paymentRequestHandler.UpdatePaymentRequest();


            }
            else
            {
               

            int payid= _paymentRequestHandler.AddAPaymentRequest();

            linkKey = payid;
            int requestTypeId = requestCreate.FindRequestTypeId("PaymentRequest");
            int id = requestCreate.CreateRequest("PaymentRequest", 0, linkKey);
            bool status = purchase.UpdateReQuestStatus(linkKey, requestTypeId, reqId);
            _RequestId = id;

              
                
                // requestlist(payid);
                Button3.Text = "Update";
            }
        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Update PaymentRequest Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }

    }
    #endregion

    #region Methods
    private bool trim(bool p)
    {
        throw new NotImplementedException();
    }
    protected void Forward_Click(object sender, EventArgs e)
    {
        if (Forward.Text == "Submit")
        {
            Save.Visible = false;
            Forward.Text = "Forward";
            UpdateRequestList(_RequestId);
            MessageBox.Show("Submited Suceessfully...");

        }
        else if (Forward.Text == "Forward")
        {
            if (linkKey != 0)
            {
                int requestTypeId = requestCreate.FindRequestTypeId("PaymentRequest");
                Session["UserManager_Control"] = "Common/ucManuallySendForApproval.ascx";
                Response.Redirect("BusinessProcessAutomation.aspx?linkKey=" + linkKey + "&RequestType=" + requestTypeId + "&RequestLinkId=" + _RequestId);
            }
            else
            {
                MessageBox.Show("Failed to Forward the Payment Request");
            }

        }
        

    }
    protected void Forward1_Click(object sender, EventArgs e)
    {
        if (Forward1.Text == "Submit")
        {
            Button3.Visible = false;
            Forward1.Text = "Forward";
            UpdateRequestList(_RequestId);
        }
        else if (Forward1.Text == "Forward")
        {
            if (linkKey != 0)
            {
                int requestTypeId = requestCreate.FindRequestTypeId("PaymentRequest");
                Session["UserManager_Control"] = "Common/ucManuallySendForApproval.ascx";
                Response.Redirect("BusinessProcessAutomation.aspx?linkKey=" + linkKey + "&RequestType=" + requestTypeId + "&RequestLinkId=" + _RequestId);
            }
            else
            {
                MessageBox.Show("Failed to Forward the Payment Request");
            }

        }
        //else if (Forward1.Text == "Forward")
        //{
        //    if (linkKey != 0)
        //    {
        //        int requestTypeId = requestCreate.FindRequestTypeId("PurchaseOrder");
        //        Session["UserManager_Control"] = "Common/ucManuallySendForApproval.ascx";
        //        Response.Redirect("BusinessProcessAutomation.aspx?linkKey=" + System.Convert.ToInt32(linkKey) + "&RequestType=" + requestTypeId + "&RequestLinkId=" + requestListUniqRecordNumber);

        //    }

        //}
      
    }
    void UpdatePaymentList(int id)
    {
        SqlConnection sqlCon = new SqlConnection();
        SqlCommand sqlCommand = new SqlCommand();

        sqlCon.ConnectionString = ((String)Session["ConnectionString"]).ToString();
        sqlCommand.Connection = sqlCon;

        sqlCon.Open();
        string sqlCmd = "update  PaymentRequestList set  RequestID='" + id + "' where PaymentID=(select LinkKey from  RequestList where RequestID='" + id + "')";
        sqlCommand.CommandText = sqlCmd;
        sqlCommand.ExecuteNonQuery();
        sqlCon.Close();


    }
    void UpdateRequestList(int rid)
     {
        SqlConnection sqlCon = new SqlConnection();
        SqlCommand sqlCommand = new SqlCommand();

        sqlCon.ConnectionString = ((String)Session["ConnectionString"]).ToString();
        sqlCommand.Connection = sqlCon;

        sqlCon.Open();
        string sqlCmd = "update RequestList  set Status=2,StepStatus=1,CurrentStep=1 where RequestID='" + _RequestId + "'";
        sqlCommand.CommandText = sqlCmd;
        sqlCommand.ExecuteNonQuery();
        sqlCon.Close();

     }
    int linkkey()
    {
        int paymentid = 0;
        try
        {
            SqlConnection sqlCon = new SqlConnection();
            SqlCommand sqlCommand = new SqlCommand();

            sqlCon.ConnectionString = ConfigurationManager.ConnectionStrings["connectUserManager"].ToString();
            sqlCommand.Connection = sqlCon;
            sqlCommand.CommandText = "SELECT MAX(paymentid) from paymentrequestlist";
            sqlCon.Open();
            SqlDataReader reader;
            reader = sqlCommand.ExecuteReader();




            while (reader.Read())
            {
                paymentid = int.Parse(reader[0].ToString());
            }
            reader.Close();
            sqlCon.Close();
        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Add PaymentRequest Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }

        return (paymentid);
    }
    int requestlist(int pid)
    {
        int id = 0;
        try
        {
            int requesterId = 0;
            if (Session["UserId"] != null)
                requesterId = Convert.ToInt16(Session["UserId"].ToString());

            _paymentreqstgenclass.Constring = ((String)Session["ConnectionString"]).ToString();


            if (Paymenttype.SelectedItem.Text.ToString().Trim() == "Incentive")
            {
                _paymentreqstgenclass.RequestTypeID = 6;

            }
            else
            {
                _paymentreqstgenclass.RequestTypeID = 3;

            }
            _paymentreqstgenclass.RequesterID = requesterId;
            _paymentreqstgenclass.RequestStatus = Convert.ToInt16(null);

            _paymentreqstgenclass.CreationTime = DateTime.Now.ToString();
            _paymentreqstgenclass.LastProcessedTime = DateTime.Now.ToString();
            //int intlinkkey = linkkey();
            _paymentreqstgenclass.LinkKey = pid;
            _paymentreqstgenclass.CurrentStep = 0;
            _paymentreqstgenclass.StepStatus = 0;
            id = _paymentreqstgenclass.AddRequestList();
            _RequestId = id;
            requestListUniqRecordNumber = _RequestId;

            return id;
        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "PaymentRequest Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }

        return id;
    }
    #endregion

}
